//  this library.
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:hktk_app/dao/my_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/my/rank_type_enum.dart';
import 'package:hktk_app/ienum/my/up_load_enum.dart';
import 'package:hktk_app/model/home/column_model.dart';
import 'package:hktk_app/model/page/resource_page_model.dart';
import 'package:hktk_app/model/subject/note_model.dart';
import 'package:hktk_app/model/subject/upload_collection_model.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/event_bus_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/mine/note_show_widget.dart';
import 'package:hktk_app/widget/mine/view_item_widget.dart';

/// 自定义返回方法
typedef InitFun = Future<List<Map<String, dynamic>>> Function(String type);

/// 我的错题显示页面
class ViewPage extends StatefulWidget {
  /// 相关信息
  final ColumnModel tabModel;

  /// 类型，0是错题，1是收藏
  final RankTypeEnum type;

  const ViewPage({
    super.key,
    required this.tabModel,
    required this.type,
  });

  @override
  State<ViewPage> createState() => _ViewPageState();
}

class _ViewPageState extends State<ViewPage> {
  late BuildContext _context;

  /// 初始化方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 相关数据方法
  late List<UploadCollectionModel> _list;

  /// 笔记相关数据
  late List<NoteModel> _noteList;

  /// 页数
  late int _current;

  /// 条数
  late int _size;

  /// 总数
  late int? _total;

  /// 列表滑动控制器
  late ScrollController _scrollController;

  /// 加载中，
  late bool _loading;

  /// 加载状态，0：什么都不显示，1：表示加载中，2：表示没有数据了
  late UploadEnum _loadType;

  /// 监听器
  late StreamSubscription<EventWrongCollectDelete> _eventWrong;

  @override
  void initState() {
    super.initState();
    debugPrint("viewPage 页面 -> initState 方法执行 ===> ${widget.tabModel.type!.desc}");
    debugPrint("");
    _scrollController = ScrollController();
    _list = [];
    _noteList = [];
    _current = 1;
    _size = 20;
    _loadType = UploadEnum.loading;
    _loading = false;
    _futureInit = _initData();

    // 监听是否滑动到底部，实现上拉加载功能
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        debugPrint("viewPage 页面 -> 滑动到底部 ===> 上拉加载更多数据");
        _loadDataInit();
      }
    });
    // 监听记录清除通知
    _eventWrong = eventBus.on<EventWrongCollectDelete>().listen((event) {
      debugPrint("viewPage 页面 -> 错题/收藏记录清除通知监听执行 ===> ");
      setState(() {
        _list = [];
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint("viewPage 页面 -> dispose 方法执行 ===> ${widget.tabModel.type!.desc}");
    debugPrint("");
    _scrollController.dispose();
    _eventWrong.cancel();
  }

  @override
  Widget build(BuildContext context) {
    _context = context;
    debugPrint("viewPage 页面 -> build 方法执行 ===> ${widget.tabModel.type!.desc}");
    debugPrint("");
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder: (
          BuildContext context,
          AsyncSnapshot<Map<String, dynamic>> snapshot,
          ) {
        if (snapshot.connectionState == ConnectionState.done) {
          var map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: _context, msg: map["msg"]);
            });
          }
          return _content();
        } else {
          // 加载中
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 加载数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      if (widget.type == RankTypeEnum.note) {
        // 最新笔记
        await _initNoteZx();
      } else {
        if (widget.type == RankTypeEnum.error) {
          // 最新错题
          await _initWrongQuestionZx();
        } else if (widget.type == RankTypeEnum.collect) {
          // 最新收藏
          await _initCollectZx();
        }
      }
      int length = _getListLength();
      // 判断数据
      if (length < _size) {
        _loadType = UploadEnum.def;
      } else if (length == _total) {
        _loadType = UploadEnum.noData;
      }

      map["suc"] = true;
    } catch (e) {
      debugPrint("viewPage 页面 -> 加载数据方法发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("viewPage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 加载错题数据方法最新
  _initWrongQuestionZx() async {
    ResourcePageModel<UploadCollectionModel> page =
    await MyDao.categoryNewsError(
      industryCode: dataUtilComm.dataModel.industryId,
      examId: dataUtilComm.dataModel.examId,
      categoryId: dataUtilComm.dataModel.categoryId,
      current: _current,
      size: _size,
    );
    if (_loading) {
      List<UploadCollectionModel> list = page.records ?? [];
      _list.addAll(list);
    } else {
      _list = page.records ?? [];
    }
    _total = page.total;
  }

  /// 加载收藏数据方法最新
  _initCollectZx() async {
    ResourcePageModel<UploadCollectionModel> page =
    await MyDao.categoryNewsCollect(
      industryCode: dataUtilComm.dataModel.industryId,
      examId: dataUtilComm.dataModel.examId,
      categoryId: dataUtilComm.dataModel.categoryId,
      current: _current,
      size: _size,
    );
    if (_loading) {
      List<UploadCollectionModel> list = page.records ?? [];
      _list.addAll(list);
    } else {
      _list = page.records ?? [];
    }
    _total = page.total;
  }

  /// 加载笔记数据方法最新
  _initNoteZx() async {
    var page = await MyDao.myNote(
      current: _current,
      size: _size,
      categoryId: dataUtilComm.dataModel.categoryId,
      newFlag: true,
    );
    if (_loading) {
      List<NoteModel> list = page.records ?? [];
      _noteList.addAll(list);
    } else {
      _noteList = page.records ?? [];
    }
    _total = page.total;
  }

  /// 内容显示方法
  Widget _content() {
    bool isEmpty =
    widget.type == RankTypeEnum.note ? _noteList.isEmpty : _list.isEmpty;
    if (isEmpty) {
      return showNoData(style: FontUtil.fontGrey2(28));
    } else {
      return MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView.builder(
          itemBuilder: _itemBuilder,
          itemCount: _getListLength() + 1,
          controller: _scrollController,
        ),
      );
    }
  }

  int _getListLength() {
    return widget.type == RankTypeEnum.note ? _noteList.length : _list.length;
  }

  /// 内容组件显示
  Widget? _itemBuilder(BuildContext context, int index) {
    if (index < _getListLength()) {
      if (widget.type == RankTypeEnum.note) {
        NoteModel noteModel = _noteList[index];
        return NoteShowWidget(
          noteModel: noteModel,
          columnType: widget.tabModel.type!,
        );
      } else {
        UploadCollectionModel collModel = _list[index];
        return ViewItemWidget(collModel: collModel, type: widget.type);
      }
    } else {
      // 提示组件
      return _tipsItem();
    }
  }

  /// 提示组件显示
  Widget? _tipsItem() {
    if (_loadType == UploadEnum.def) {
      return null;
    } else if (_loadType == UploadEnum.loading) {
      // 加载中
      return SizedBox(
        height: 100,
        child: Center(
          child: SizedBox(
            width: 40,
            height: 40,
            child: CircularProgressIndicator(
              strokeWidth: 4,
            ),
          ),
        ),
      );
    } else if (_loadType == UploadEnum.noData) {
      // 没有数据，我是有底线的
      return showListEnd();
    }
    return null;
  }

  /// 上拉加载功能
  void _loadDataInit() {
    debugPrint("viewPage 页面 -> 上拉加载更多 ===> $_loading");
    if (_loadType == UploadEnum.def) {
      setState(() {
        _loadType = UploadEnum.noData;
      });
    } else if (_loadType == UploadEnum.loading) {
      if (!_loading) {
        _loading = true;
        _current++;
        _initData().then((Map<String, dynamic> map) {
          // 加载完成
          if (!map["suc"]) {
            ToastUtil.show(context: _context, msg: map["msg"]);
          }
          setState(() {
            _loading = false;
          });
        });
      }
    }
  }
}
